package com.zsl.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.List;

@WebListener
public class OnlineCountingListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
    ServletContext application = null;

    //监听初始化的时候
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //用一个列表保存用户的信息
        List<String> list = new ArrayList<String>();
        //取得Context对象
        application = servletContextEvent.getServletContext();
        //将用户列表放入
        application.setAttribute("allUser", list);
    }

    //当监听关闭时（服务器被关闭
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("服务器关闭");
    }

    //当Session中添加的新的属性时（也就是有用户登录了
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        List<String> list = (List<String>) application.getAttribute("allUser");
        //假设：用户登陆成功之后，只将户名设置到session中
        if (((String) httpSessionBindingEvent.getName()).equals("user")) {
            System.out.println("添加：" + (String) httpSessionBindingEvent.getSession().getAttribute("user"));
            String userName = (String) httpSessionBindingEvent.getSession().getAttribute("user");
            //取得用户名
            if (list.indexOf(userName) == -1) {
                //表示此用户之前没有登陆
                list.add(userName);
                application.setAttribute("allUser", list);
            }
        }
    }

    //当Session中某个用户退出登录了
    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        //只对user敏感
        if (((String) httpSessionBindingEvent.getName()).equals("user")) {
            List<String> list = (List<String>) application.getAttribute("allUser");
            System.out.println("移出：" + (String) httpSessionBindingEvent.getValue());
            list.remove((String) httpSessionBindingEvent.getValue());
            application.setAttribute("allUser", list);
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {

    }
}
